import React from 'react';
import PropTypes from 'prop-types';
import cn from 'classnames';
import { withRouter } from 'react-router';
import { Link } from 'react-router-dom';
import pathOr from 'ramda/es/pathOr';
import { gql, useMutation } from '@apollo/client';

import Button from '@kuiper-components/button';
import PageTable, { searchStringBuilder } from '@kuiper-components/page-table';
import CopyBoard from '../../../../components/CopyBoard';
import s from './URL.module.css';
import Label from '../../../../components/Label';
import HostSearchInput from '../../../../components/HostSearchInput';
import confirm from '../../../../components/confirm';
import { datetime } from '../../../../../common/formatter';
import { TASK_TYPE_CATEGORY_MAP } from '../../../../../common/constants';

const BLACKLIST_REMOVE_GQL = gql`
	mutation YunAQBlacklistRemoveOne($input: [String]!, $formSerializer: any) {
		publish(input: $input)
			@rest(
				type: "YunaqBlacklistRemoveOneResponse"
				path: "/cloud/udb_del_blacklist"
				method: "POST"
				bodySerializer: $formSerializer
				endpoint: "v2"
			) {
			code
			msg
		}
	}
`;

function queryGQLBuilder() {
	return gql`
		query YunAQBlacklist(
			$searchKey: String = ""
			$page: Int = 1
			$limit: Int = 10
		) {
			dataPgination(searchKey: $searchKey, page: $page, limit: $limit)
				@rest(
					type: "YunaqBlacklistResponse"
					path: "/cloud/udb_get_blacklist?{args}"
					endpoint: "v2"
				) {
				code
				msg
				results {
					count
					data {
						_id
						addType: add_type
						createTime: create_time
						detail
						note
						jobId: job_id
						triggerType
						asset_task_id
						targetUrl
						taskId: task_id
						taskType: task_type
						url
					}
				}
			}
		}
	`;
}

const queryVariablesBuilder = ({ filter, page, perPage }) => ({
	page,
	limit: perPage,
	searchKey: filter?.searchKey,
});
const getTotal = pathOr(1, ['dataPgination', 'results', 'count']);
const getTableRows = pathOr([], ['dataPgination', 'results', 'data']);
const getTablePageInfo = ({ tableData, variables }) => ({
	currentPage: variables.page,
	perPage: variables.perPage,
	pageCount: Math.ceil(getTotal(tableData) / variables.perPage),
});

function URL({ className, location, history }) {
	const [selectedRows, setSelectedRows] = React.useState({});
	const handleRowSelectionChange = rows => setSelectedRows(rows);
	const [refetch, setRefetch] = React.useState(null);

	const [remove] = useMutation(BLACKLIST_REMOVE_GQL);
	const handleRemove = blacklistIds =>
		confirm.warning({
			message:
				'删除选中风险URL将同步删除在知道创宇云防御平台URL黑名单功能里设置的对应数据，您确定要删除吗？',
			okText: '确定',
			cancelText: '取消',
			title: '提示',
			onOk: () =>
				remove({
					variables: {
						input: { blacklistIds },
					},
				}).then(() => {
					setSelectedRows({});
					refetch && refetch();
				}),
		});
	const search = new URLSearchParams(location.search);
	const filter = JSON.parse(
		decodeURIComponent(search.get('filter') || '') || '{}'
	);
	const handleSearch = searchKey => {
		const search = searchStringBuilder(location.search, {
			filter: JSON.stringify({ searchKey }),
			page: 1,
		});
		history.replace(`/yfld/blacklist/url?${search}`);
	};

	const columns = React.useMemo(
		() => [
			{
				title: '风险URL',
				dataIndex: 'url',
				key: 'url',
				width: 480,
				render(url) {
					return (
						<CopyBoard className={s.target2} text={url}>
							{url}
						</CopyBoard>
					);
				},
			},
			{
				title: '生效时间',
				dataIndex: 'createTime',
				key: 'createTime',
				render: datetime,
			},
			{
				title: '添加类型',
				dataIndex: 'addType',
				key: 'addType',
			},
			{
				title: '资产名称',
				dataIndex: 'note',
				key: 'note',
			},
			{
				title: '资产地址',
				dataIndex: 'targetUrl',
				key: 'targetUrl',
				render(targetUrl) {
					return (
						<CopyBoard className={s.target} text={targetUrl}>
							{targetUrl}
						</CopyBoard>
					);
				},
			},
			{
				title: '操作',
				dataIndex: '_id',
				key: '__actions__',
				className: s.action,
				width: 96,
				// eslint-disable-next-line react/display-name
				render: (
					_id,
					{
						detail,
						taskType,
						taskId,
						asset_task_id,
						triggerType,
						targetUrl,
						jobId,
					}
				) => {
					return (
						<div className={s.content}>
							<Button
								link
								primary
								className={s.btn}
								onClick={() =>
									confirm.normal({
										message: detail,
										okText: '监测详情',
										cancelText: '取消',
										title: '详情',
										onOk: () => {
											const url = () => {
												if (triggerType) {
													const taskType_ =
														taskType === 'securityEvent'
															? 'security_event'
															: taskType;
													if (
														triggerType === 'schedule' ||
														triggerType === 'scheduleIncrement'
													) {
														return `/job-manage/web-task/history?asset_task_id=${asset_task_id}&task_id=${taskId}&task_types=${taskType_}`;
													} else {
														return `/job-manage/web-task/detail?id=${asset_task_id}&type=${triggerType}&jid=${jobId}&tag=${taskType_}`;
													}
												} else {
													return `/job-manage/web-task?filter=${encodeURI(
														JSON.stringify({ target_url: targetUrl })
													)}`;
												}
											};
											history.push(url());
										},
									})
								}
							>
								查看
							</Button>
							<Button
								link
								primary
								className={s.btn}
								onClick={() => handleRemove([_id])}
							>
								删除
							</Button>
						</div>
					);
				},
			},
		],
		[refetch]
	);

	return (
		<div className={cn(className, s.url)}>
			<Label note="以下添加的URL资产将联动云防御平台相应域名URL黑名单功能，一键加黑页面，及时缓解业务系统威胁。">
				URL黑名单
			</Label>
			<div className={s.toolbox}>
				<Link to="/yfld/blacklist/strategy?create">
					{/* <Button primary className={s.addBtn}>
						添加策略
					</Button> */}
				</Link>
				<HostSearchInput
					placeholder="请输入搜索内容"
					value={filter.searchKey}
					onChange={handleSearch}
				/>
			</div>
			<PageTable
				className={s.table}
				routePrefix="/yfld/blacklist/url"
				rowSelected={selectedRows}
				onRowSelectionChange={handleRowSelectionChange}
				columns={columns}
				getRefetch={x => refetch || setRefetch(() => x)}
				queryGQLBuilder={queryGQLBuilder}
				queryVariablesBuilder={queryVariablesBuilder}
				getTotal={getTotal}
				getTableRows={getTableRows}
				getTablePageInfo={getTablePageInfo}
				rightBottomContent={
					<Button
						link
						primary
						disabled={Object.keys(selectedRows).length <= 0}
						onClick={() =>
							handleRemove(
								Object.entries(selectedRows).reduce((arr, [id, selected]) => {
									if (selected) arr.push(id);
									return arr;
								}, [])
							)
						}
					>
						批量删除
					</Button>
				}
			/>
		</div>
	);
}

URL.propTypes = {
	className: PropTypes.string,
	location: PropTypes.shape({
		search: PropTypes.string.isRequired,
	}).isRequired,
	history: PropTypes.shape({
		push: PropTypes.func.isRequired,
		replace: PropTypes.func.isRequired,
	}).isRequired,
};

URL.defaultProps = {
	className: s.url,
};

export default withRouter(URL);
